/*
 * @Author: zhangxin 411020991@qq.com
 * @Date: 2025-09-23 14:02:03
 * @LastEditors: zhangxin 411020991@qq.com
 * @LastEditTime: 2025-10-23 16:14:40
 * @FilePath: \子应用2\src\pages\ETrade\PowerGenerationPlan\components\GenerationPlan\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React from 'react';
import { useDebounceFn } from 'ahooks';
import {
  Button,
  ConfigProvider,
  DatePicker,
  Form,
  InputNumber,
  message,
  Popconfirm,
  Select,
  Steps,
} from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import moment from 'moment';

import { HttpCode } from '#/utils/contacts.js';
import { CalendarOutlined } from '#/utils/antdIcons.js';
import { PageLoading, TRDefault } from '@/components/index.js';

import {
  getStationsByIds,
  querypowerGenerationData,
  saveYearToMonthPowerGenerationPlan,
  useNewServers,
} from '../../services.js';
import { MonthRatioTable, YearRatioTable } from '../BaseTable';
import CheckedList from '../CheckedList';
import styles from './index.less';

import {
  configureRadiusSvg,
  OPTION_KEY,
  tableHead_2,
  tableHead_3,
  tableHead_4,
  tableHead_4_PXBNX,
  YearOptions,
  // @ts-ignore
} from '../../helper';
// @ts-ignore
import { ChartDealAllPowerBar, ChartDealMonthLine } from '../Charts';
import AdjustScale from './componets/AdjustScale';
import SetScale from './componets/SetScale';
import MakePlan from './componets/MakePlan';

const { Step } = Steps;
let isFirst = false;

const MySelect = (props: any) => {
  const { value = [], onChange, options = [] } = props;
  return (
    <>
      <Select
        showSearch={false}
        value={value}
        options={options}
        style={{ width: 216 }}
        placeholder="请选择参考年份"
        mode="multiple"
        maxTagCount={1}
        maxTagTextLength={4}
        onChange={onChange}
        dropdownRender={() =>
          options.length ? (
            <CheckedList options={options} onChange={onChange} value={value} />
          ) : (
            <TRDefault type="emptysm" />
          )
        }
      />
      <CalendarOutlined className={styles.icon_calendar} />
    </>
  );
};
const PowerGenerationPlanSurvey = ({
  stations,
  reSize,
  selectData,
  save,
  editable = true,
  year,
  setIsTimeShow,
  setQueryData,
  refreshCount,
  setDataCount,
}: any) => {
  const [current, setCurrent] = React.useState(0),
    [loading, setLoading] = React.useState(false),
    [form] = Form.useForm(),
    [ratioTableData, setRatioTableData] = React.useState<any>(),
    [yearTableData, setYearTableData] = React.useState<any>(),
    [detailTableData, setDetailTableData] = React.useState<any>([]),
    [ehartDealYearBarData, setEhartDealYearBarData] = React.useState<any>({}), //计划参考柱状（年计划）
    [echartsPlanMonthLineData, setEchartsPlanMonthLineData] = React.useState<any>({}), //计划参考（月计划）
    [referenceYearOptions, setReferenceYearOptions] = React.useState(), //参考年份列表
    [inputValue, setInputValue] = React.useState<any>(0),
    [adjustScaleData, setAdjustScaleData] = React.useState<any>(),
    [ValueData, setValueData] = React.useState<any>(),
    [btnLoading, setBtnLoading] = React.useState<any>(false),
    [isSave, setIsSave] = React.useState(false),
    // [isTag, setIsTag] = React.useState(false),
    [showSavePop, setShowSavePop] = React.useState(false),
    [showPublicPop, setShowPublicPop] = React.useState(false),
    [maxYearEle, setMaxYearEle] = React.useState(0),
    [planStatus, setPlanStatus] = React.useState<any>(null),
    [formData, setFormData] = React.useState<any>({}),
    [marketId, setMarketId] = React.useState<string>('');

  //处理返回数据的状态
  const checkStatus = (val: any) => {
    //状态是数组表示包含多个状态
    if (val?.length > 1) {
      if (val.includes('1') && !val.includes('-1')) {
        return '1';
      } else {
        return null;
      }
    } else {
      //状态是字符串 制定状态
      if (val?.includes('2')) {
        return '2';
      } else if (val?.includes('1') && !val?.includes('-1')) {
        return '1';
      } else {
        return null;
      }
    }
  };

  const _setDetailData = (data: any) => {
    setDetailTableData(data);
  };
  const onTagChange = (value: number) => {
    setCurrent(value);
    form.submit();
  };
  const initialValues = () => {
    return {
      date: moment(year),
      plan: '0',
      unit: selectData?.unitId,
    };
  };
  //月份数据加总
  const monthToYear = (val: any) => {
    return !val?.length
      ? '0'
      : parseFloat(
          val.reduce(
            (a: number, b: number) =>
              parseFloat(parseFloat(a || (0 as any)).toFixed(3)) +
              parseFloat(parseFloat(b || (0 as any)).toFixed(3)),
          ),
        ).toFixed(3);
  };
  const descSort = (val: any) => {
    return val.sort((a: any, b: any) => {
      return b.title.substring(0, 4) === a.title.substring(0, 4)
        ? a.title.includes('计划')
          ? -1
          : 0
        : b.title.substring(0, 4) - a.title.substring(0, 4);
    });
  };
  //处理表格数据
  const getNewTableData = (data: any, monthCapacity: any = []) => {
    if (current === 1) {
      let _data: any = [];
      const radio: any = [],
        currentYearData: any = [0];
      //年计划
      Object.entries(data).forEach((t: any) => {
        let _temp: any = [];
        Object.entries(t[1]?.numerical).forEach((_t: any) => {
          if (_t[0] === moment(form.getFieldValue('date')).format('YYYY')) {
            // if (!isTag) {
            Object.entries(_t[1]).forEach((_t_: any) => {
              if (_t_[0].includes('plan')) {
                const _currentYearData = monthToYear(_t_[1]);
                setInputValue(_currentYearData);
                currentYearData[0] = _currentYearData;
              }
              if (marketId === 'PXBNX') {
                if (_t_[0].includes('settlement')) {
                  const _currentYearData = monthToYear(_t_[1]);
                  currentYearData[1] = _currentYearData;
                }
              }
            });
            // }
            const maxEle: any = parseFloat(
              (monthCapacity[0].stationCapacity * 10 * 24 * 365) as any,
            ).toFixed(3);
            setMaxYearEle(maxEle);
            return;
          }
          _temp.push({
            title: _t[0] + '年参考电量',
          });
          Object.entries(_t[1]).forEach((_t_: any) => {
            const allEmpty = _t_[1].every((k: any) => k === null); //十二个月全为null
            if (!allEmpty) {
              _temp[_temp.length - 1][`${_t_[0]}`] = monthToYear(_t_[1]);
            }
          });
        });
        if (_temp[0]?.title) {
          _data = descSort(_temp);
        }

        _temp = [];
        //月度分解比例
        Object.entries(t[1]?.proportion).forEach((_t: any) => {
          Object.entries(_t[1]).forEach((x: any) => {
            let title = '';
            const count = '',
              month: any = {};
            if (x[0].includes('plan')) {
              title = _t[0] + '年计划比例';
            }
            if (x[0].includes('operate')) {
              title = _t[0] + '年经营比例';
            }
            if (x[0].includes('guoneng')) {
              title = _t[0] + '年国能日新预测比例';
            }
            if (x[0].includes('huineng')) {
              title = _t[0] + '年金风慧能预测比例';
            }
            if (x[0].includes('settlement')) {
              title = _t[0] + '年结算比例';
            }
            let allEmpty = 0; //十二个月中为null的个数
            x[1]?.forEach((y: any, i: number) => {
              if (y === null) {
                allEmpty++;
              }
              month[OPTION_KEY[i + 1]] = y !== null ? parseFloat((y * 100) as any).toFixed(2) : y;
            });
            if (allEmpty < 12) {
              _temp.push({
                title,
                count,
                ...month,
              });
            }
          });
        });
        const str = moment(form.getFieldValue('date')).format('YYYY') + '年计划比例';
        const top = _temp.filter((item: any) => item.title === str);
        setValueData(_temp); //设置比例数据
        if (top.length) {
          _temp = _temp.map((item: any) => {
            //设置首行可编辑
            if (item.title === str) {
              item.editor = 1;
              let _num = 0;
              //不存在的数据转0
              Object.values(OPTION_KEY).forEach((_t: any) => {
                if (!item[_t]) {
                  item[_t] = 0;
                }
                //总比例超过100% 则最多100%
                if (parse(_num, parseFloat(item[_t] as string), 'add') >= 100) {
                  item[_t] = parse(100, _num, 'reduce');
                  _num = 100;
                } else {
                  _num = parse(_num, item[_t], 'add');
                }
                //最后一个月 总比例仍小于100% 补到十二月
                if (_t === 'December' && _num < 100) {
                  item[_t] = parse(100, _num, 'reduce');
                }
              });
            }
            return item;
          });
        } else {
          _temp.unshift({
            title: str,
            January: '0',
            February: '0',
            March: '0',
            April: '0',
            May: '0',
            June: '0',
            July: '0',
            August: '0',
            September: '0',
            October: '0',
            November: '0',
            December: '0',
            editor: 1,
          });
        }
        _temp = descSort(_temp);
        radio.push(_temp);
      });
      return { _data, radio, currentYearData };
    } else {
      //月计划
      const value: any = [];
      Object.entries(data).forEach((t: any) => {
        let _temp: any = [];
        setPlanStatus(checkStatus(t[1]?.status));
        //月度计划发电明细
        Object.entries(t[1]?.numerical).forEach((_t: any) => {
          Object.entries(_t[1]).forEach((x: any) => {
            let count: any = '',
              title = '';
            const month: any = {};
            if (x[0].includes('plan')) {
              title = _t[0] + '年计划电量';
            }
            if (x[0].includes('operate')) {
              title = _t[0] + '年经营电量';
            }
            if (x[0].includes('guoneng')) {
              title = _t[0] + '年国能日新预测电量';
            }
            if (x[0].includes('huineng')) {
              title = _t[0] + '年金风慧能预测电量';
            }
            if (x[0].includes('settlement')) {
              title = _t[0] + '年结算电量';
            }
            count = monthToYear(x[1]);
            let allEmpty = 0; //十二个月中为null的个数
            x[1]?.forEach((y: any, i: number) => {
              if (y === null) {
                allEmpty++;
              }
              month[OPTION_KEY[i + 1]] = y !== null ? parseFloat(y).toFixed(3) : y;
              month[`${OPTION_KEY[i + 1]}_Capacity`] = parseFloat(
                (monthCapacity[0].stationCapacity *
                  24 *
                  10 *
                  moment().month(i).daysInMonth()) as any,
              ).toFixed(3);
            });
            //假数据不展示
            if (allEmpty < 12) {
              _temp.push({
                title,
                count,
                ...month,
              });
            }
          });
        });
        const str = moment(form.getFieldValue('date')).format('YYYY') + '年计划电量';
        const top = _temp.filter((item: any) => item.title === str);
        setAdjustScaleData(_temp); //一键调整数据
        if (top.length) {
          _temp = _temp.map((item: any) => {
            if (item.title === str) {
              item.editor = 1;
              //不存在的数据转0
              Object.values(OPTION_KEY).forEach((_t: any) => {
                if (!item[_t]) {
                  item[_t] = 0;
                }
              });
            }
            return item;
          });
        } else {
          const topData: any = {
            count: 0,
            January: '0',
            February: '0',
            March: '0',
            April: '0',
            May: '0',
            June: '0',
            July: '0',
            August: '0',
            September: '0',
            October: '0',
            November: '0',
            December: '0',
          };
          Object.keys(topData).forEach((_t: any, i: number) => {
            topData[`${OPTION_KEY[i + 1]}_Capacity`] = parseFloat(
              (monthCapacity[0].stationCapacity * 24 * 10 * moment().month(i).daysInMonth()) as any,
            ).toFixed(3);
          });
          topData.editor = 1;
          topData.title = str;
          _temp.unshift(topData);
        }
        _temp = descSort(_temp);
        value.push(_temp);
      });
      return { value };
    }
  };

  const _onFinish = useDebounceFn(
    async (values: any) => {
      //通过stationId去查找marketId
      const result = stations.find((item: any) => item.stationId === values.unit);
      let _marketId = '';
      if (result) {
        setMarketId(result.marketId);
        _marketId = result.marketId;
      }
      setLoading(true);
      setRatioTableData([]);
      setDetailTableData([]);
      setYearTableData([]);
      setEchartsPlanMonthLineData({});
      // if (!isTag) {
      setInputValue(0);
      // }
      setFormData(values);
      setQueryData(values);
      const _formData: any = values,
        _date = moment(_formData.date).format('YYYY'),
        _referenceYear = _formData.referenceYear || [],
        _unit = _formData.unit;
      const referenceYearParams = _referenceYear.map((t: any) => {
        return {
          dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
          year: t,
        };
      });
      const param: any = {
        planStatus: null,
        // planStatus: planStatus,
        reqDataScopes: [
          {
            dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
            year: _date,
          },
          ...referenceYearParams,
        ],
        respDataTypes: ['numerical', 'proportion'],
        stationIds: [_unit],
      };

      if (useNewServers.includes(_marketId)) {
        param.marketId = _marketId;
      }

      const res = await Promise.all([
        querypowerGenerationData(param, _marketId),
        getStationsByIds({ stationIds: [_unit] }, _marketId),
      ]);
      if (res[0]?.statusCode === HttpCode.SUCCESS && res[1]?.statusCode === HttpCode.SUCCESS) {
        if (current === 1) {
          const { _data, radio, currentYearData } = getNewTableData(res[0].data || {}, res[1].data);
          setRatioTableData(radio[0]);
          setYearTableData(_data);
          const dataArray = [{ name: _date + '年', data: currentYearData }];
          _data.forEach((t: any) => {
            if (marketId === 'PXBNX') {
              dataArray.push({
                name: t.title.split('参')[0],
                data: [t.plan, t.settlement],
              });
            } else {
              dataArray.push({
                name: t.title.split('参')[0],
                data: [t.plan, t.operate, t.settlement, t.guoneng, t.huineng],
              });
            }
          });
          let head = tableHead_4;
          if (marketId === 'PXBNX') {
            head = tableHead_4_PXBNX;
          }
          setEhartDealYearBarData({
            XAXIS: head.map((t: any) => t.name),
            dataArray,
          });
        } else {
          //处理表格数据
          if (!res[1].data?.length) {
            return;
          }
          const arr = res[0].data?.[_unit]?.numerical?.[_date]?.plan;
          setDataCount(arr);
          const data = getNewTableData(res[0].data || {}, res[1].data);
          const { value }: any = data;
          setDetailTableData(value[0]);
          setEchartsPlanMonthLineData({
            XAXIS: [
              '1月',
              '2月',
              '3月',
              '4月',
              '5月',
              '6月',
              '7月',
              '8月',
              '9月',
              '10月',
              '11月',
              '12月',
            ],
            dataArray: value[0],
          });
        }
      }
      setLoading(false);
    },
    { wait: 500 },
  );

  //通过stationId去查找marketId
  const getMarketId = (unit: string) => {
    const result = stations.find((item: any) => item.stationId === unit);
    let _marketId = '';
    if (result) {
      _marketId = result.marketId;
    }
    return _marketId;
  };

  const onSetpHanlder = async () => {
    setBtnLoading(true);
    if (editable) {
      if (current === 0) {
        //如果是已完成 点击保存下一步 则年计划查询‘修改待发布’的数据
        if (planStatus === 1 || planStatus === '1') {
          setPlanStatus(2);
        }
        const param: any = {
          monthEle: {},
          stationId: form.getFieldValue('unit'),
          valueType: 'numerical',
          year: moment(formData.date).format('YYYY'),
          publish: false,
          yearEle: detailTableData[0].count,
        };
        Object.values(OPTION_KEY).map((_t: any, i: number) => {
          param.monthEle[i + 1] = detailTableData[0][OPTION_KEY[i + 1]];
        });

        const marketId = getMarketId(form.getFieldValue('unit'));
        if (useNewServers.includes(marketId)) {
          param.marketId = marketId;
        }
        const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
        if (res?.statusCode === HttpCode.SUCCESS) {
        } else {
          message.error(res.message);
        }
      } else {
        let _num = 0;
        Object.values(OPTION_KEY).map((key: any) => {
          _num = parse(_num, ratioTableData[0][key], 'add');
        });
        if (_num < 100) {
          message.error('当前比例不足100%');
          setBtnLoading(false);
          return;
        } else if (_num > 100) {
          message.error('当前比例超过100%');
          setBtnLoading(false);
          return;
        } else {
          const param: any = {
            monthEle: {},
            stationId: form.getFieldValue('unit'),
            valueType: 'proportion',
            year: moment(formData.date).format('YYYY'),
            publish: false,
            yearEle: inputValue,
          };
          Object.values(OPTION_KEY).map((_t: any, i: number) => {
            param.monthEle[i + 1] = parseFloat(
              (ratioTableData[0][OPTION_KEY[i + 1]] / 100) as any,
            ).toFixed(4);
          });

          const marketId = getMarketId(form.getFieldValue('unit'));
          if (useNewServers.includes(marketId)) {
            param.marketId = marketId;
          }
          const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
          if (res?.statusCode === HttpCode.SUCCESS) {
          } else {
            message.error(res.message);
          }
        }
      }
    }

    setBtnLoading(false);
    setCurrent(current ? 0 : 1);
    form.submit();
  };
  const onUnitChange = async () => {
    setPlanStatus(null); //切换交易单元重置状态
    //首次加载
    if (isFirst) {
      isFirst = false;
      form.submit();
    }
  };
  //单个月明细 输入框change
  const onValueChange = (value: number | string, field: any) => {
    const dataTable = [...detailTableData];
    const defaultValue = value && value > 0 ? parseFloat(parseFloat(value as any).toFixed(3)) : 0;
    if (defaultValue - dataTable[0][field + '_Capacity'] > 0) {
      dataTable[0][field] = dataTable[0][field + '_Capacity'];
    } else {
      dataTable[0][field] = defaultValue;
    }
    const arr: any = [];
    Object.values(OPTION_KEY).forEach((t: any) => {
      arr.push(dataTable[0][t]);
    });
    dataTable[0].count = monthToYear(arr);
    setDetailTableData(dataTable);
  };
  //月度计划发电明细 一键调整
  const _onAdjustValue = async () => {
    let haveSettlement: any = [];
    const _temp = adjustScaleData.filter((t: any) => {
      if (
        t.title.includes(moment(form.getFieldValue('date')).format('YYYY')) &&
        !t.title.includes('计划')
      ) {
        haveSettlement = [moment(form.getFieldValue('date')).format('YYYY')];
        return t;
      }
      const re = (form.getFieldValue('referenceYear') || []).some((_t: any) => {
        return (
          t.title.includes(_t) &&
          (t.title.includes('计划电量') ||
            t.title.includes('结算电量') ||
            t.title.includes('经营电量') ||
            t.title.includes('预测电量'))
        );
      });
      if (re) {
        return t;
      }
    });
    const _options = haveSettlement
      .concat(form.getFieldValue('referenceYear') || [])
      .map((_t: any) => ({ label: _t, value: _t }));
    const result: any = await AdjustScale.show({
      referencePowerData: descSort(_temp),
      referenceYearOptions: _options,
    });
    if (result?.index === 1) {
      //全部重置
      if (result.clear) {
        const newData = detailTableData.map((t: any, i: number) => {
          if (i === 0) {
            t.count = 0;
            Object.values(OPTION_KEY).forEach((_t: any) => {
              t[_t] = 0;
            });
            return t;
          }
          return t;
        });
        setDetailTableData(newData);
      } else {
        const checkedData = result?.checkedData || {};
        Object.values(OPTION_KEY).forEach((_t: any) => {
          onValueChange(checkedData[_t], _t);
        });
      }
    }
    AdjustScale.dismiss();
  };
  //步加|步减
  function parse(data: number, data_2: number, type: 'add' | 'reduce') {
    switch (type) {
      case 'add':
        return (data * 1000 + data_2 * 1000) / 1000;
      case 'reduce':
        return (data * 1000 - data_2 * 1000) / 1000;
    }
  }
  //单个月比例 输入框change
  const onRatioChange = (value: number | string, field: any) => {
    const dataTable = [...ratioTableData];
    const defaultValue = value && value > 0 ? parseFloat(value as any).toFixed(2) : 0;
    let _compare = parse(parseFloat(defaultValue as string), dataTable[0][field], 'reduce');
    //步减
    if (_compare > 0) {
      //其他项总和
      let _num = 0;

      Object.values(OPTION_KEY).map((key: any) => {
        if (key !== field) {
          _num = parse(_num, dataTable[0][key], 'add');
        }
      });
      //总和超过100%
      if (parse(_num, parseFloat(defaultValue as string), 'add') >= 100) {
        //超过100%差值重新计算
        _compare = parse(100, _num, 'reduce') - dataTable[0][field];

        dataTable[0][field] = parse(100, _num, 'reduce');
      } else {
        dataTable[0][field] = defaultValue;
      }
    } else {
      dataTable[0][field] = defaultValue;
    }
    setRatioTableData(dataTable);
  };
  //月分解比例 设置比例
  const _onSetScale = async () => {
    const _temp = ValueData.filter((t: any) => {
      const re = (form.getFieldValue('referenceYear') || []).some((_t: any) => {
        return (
          t.title.includes(_t) &&
          (t.title.includes('计划比例') ||
            t.title.includes('结算比例') ||
            t.title.includes('经营比例') ||
            t.title.includes('预测比例'))
        );
      });
      if (re) {
        return t;
      }
    });
    const result: any = await SetScale.show({
      referencePowerData: _temp,
      planYear: moment(form.getFieldValue('date')).format('YYYY'),
    });

    if (result?.index === 1) {
      onRatioChange(result.value, OPTION_KEY[result.month]);
    }

    SetScale.dismiss();
  };
  //年计划 按比例制定计划
  const _onMakePlan = async () => {
    const result: any = await MakePlan.show({
      referencePowerData: yearTableData,
      planYear: moment(form.getFieldValue('date')).format('YYYY'),
    });

    if (result?.index === 1) {
      setInputValue(result.value);
    }

    MakePlan.dismiss();
  };
  //发布
  const onPublic = async () => {
    if (current === 0) {
      const param: any = {
        monthEle: {},
        stationId: form.getFieldValue('unit'),
        valueType: 'numerical',
        year: moment(formData.date).format('YYYY'),
        publish: true,
        yearEle: detailTableData[0].count,
      };
      Object.values(OPTION_KEY).map((_t: any, i: number) => {
        param.monthEle[i + 1] = detailTableData[0][OPTION_KEY[i + 1]];
      });

      const marketId = getMarketId(form.getFieldValue('unit'));
      if (useNewServers.includes(marketId)) {
        param.marketId = marketId;
      }
      const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('发布成功');
        save();
      } else {
        message.error('发布失败');
      }
    } else {
      const param: any = {
        monthEle: {},
        stationId: form.getFieldValue('unit'),
        valueType: 'proportion',
        year: moment(formData.date).format('YYYY'),
        publish: true,
        yearEle: inputValue,
      };
      Object.values(OPTION_KEY).map((_t: any, i: number) => {
        param.monthEle[i + 1] = parseFloat(
          (ratioTableData[0][OPTION_KEY[i + 1]] / 100) as any,
        ).toFixed(4);
      });
      const marketId = getMarketId(form.getFieldValue('unit'));
      if (useNewServers.includes(marketId)) {
        param.marketId = marketId;
      }
      const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('发布成功');
        save();
      } else {
        message.error('发布失败');
      }
    }
  };
  //发布保存前 检查
  const checked = (type: any) => {
    //显隐保存/发布按钮上方提示
    let _empty = true;
    if (current === 1) {
      let _num = 0;

      Object.values(OPTION_KEY).map((key: any) => {
        _num = parse(_num, ratioTableData[0][key], 'add');
      });
      if (_num < 100) {
        message.error('当前比例不足100%');
      } else if (_num > 100) {
        message.error('当前比例超过100%');
      } else {
        type === 'save' ? setShowSavePop(true) : setShowPublicPop(true);
      }
    }
    if (current === 0) {
      type === 'save' ? setShowSavePop(true) : setShowPublicPop(true);
      Object.values(OPTION_KEY).map((_t: any, i: number) => {
        if (!_empty) return;
        _empty = detailTableData[0][OPTION_KEY[i + 1]] > 0;
      });
    }
    setIsSave(_empty);
  };
  //保存
  const onSave = async () => {
    if (current === 0) {
      const param: any = {
        monthEle: {},
        stationId: form.getFieldValue('unit'),
        valueType: 'numerical',
        year: moment(formData.date).format('YYYY'),
        publish: false,
        yearEle: detailTableData[0].count,
      };
      Object.values(OPTION_KEY).map((_t: any, i: number) => {
        param.monthEle[i + 1] = detailTableData[0][OPTION_KEY[i + 1]];
      });
      const marketId = getMarketId(form.getFieldValue('unit'));
      if (useNewServers.includes(marketId)) {
        param.marketId = marketId;
      }
      const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('保存成功');
        save();
      } else {
        message.error('保存失败');
      }
    } else {
      const param: any = {
        monthEle: {},
        stationId: form.getFieldValue('unit'),
        valueType: 'proportion',
        year: moment(formData.date).format('YYYY'),
        publish: false,
        yearEle: inputValue,
      };
      Object.values(OPTION_KEY).map((_t: any, i: number) => {
        param.monthEle[i + 1] = parseFloat(
          (ratioTableData[0][OPTION_KEY[i + 1]] / 100) as any,
        ).toFixed(4);
      });
      const marketId = getMarketId(form.getFieldValue('unit'));
      if (useNewServers.includes(marketId)) {
        param.marketId = marketId;
      }
      const res = await saveYearToMonthPowerGenerationPlan(param, marketId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('保存成功');
        save();
      } else {
        message.error('保存失败');
      }
    }
  };
  //计划年日期
  const onDateChange = async (data: any) => {
    const temp: any = YearOptions(moment(data).format('YYYY'));
    setReferenceYearOptions(temp);
    form.setFieldsValue({ referenceYear: [temp[0].value] });
  };
  //计划年电量 输入框
  const onInputChange = (e: any) => {
    const defaultValue = e && e > 0 ? parseFloat(parseFloat(e as any).toFixed(3)) : 0;
    setInputValue(defaultValue || 0);
  };

  React.useEffect(() => {
    onDateChange(moment(year));
    if (selectData?.unitId) {
      isFirst = true;
      onUnitChange();
      if (!(selectData?.status instanceof Array)) {
        setPlanStatus(selectData?.status);
      }
    }
  }, []);

  const updateFetch = async () => {
    try {
      // 获取表单值
      const values = await form.validateFields();
      //通过stationId去查找marketId
      const result = stations.find((item: any) => item.stationId === values.unit);
      let _marketId = '';
      if (result) {
        setMarketId(result.marketId);
        _marketId = result.marketId;
      }
      setLoading(true);
      setRatioTableData([]);
      setDetailTableData([]);
      setYearTableData([]);
      setEchartsPlanMonthLineData({});
      // if (!isTag) {
      setInputValue(0);
      // }
      setFormData(values);
      setQueryData(values);
      const _formData: any = values,
        _date = moment(_formData.date).format('YYYY'),
        _referenceYear = _formData.referenceYear || [],
        _unit = _formData.unit;
      const referenceYearParams = _referenceYear.map((t: any) => {
        return {
          dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
          year: t,
        };
      });
      const param: any = {
        planStatus: null,
        // planStatus: planStatus,
        reqDataScopes: [
          {
            dataTypeList: ['settlement', 'operate', 'huineng', 'guoneng', 'plan'],
            year: _date,
          },
          ...referenceYearParams,
        ],
        respDataTypes: ['numerical', 'proportion'],
        stationIds: [_unit],
      };

      if (useNewServers.includes(_marketId)) {
        param.marketId = _marketId;
      }

      const res = await Promise.all([
        querypowerGenerationData(param, _marketId),
        getStationsByIds({ stationIds: [_unit] }, _marketId),
      ]);
      if (res[0]?.statusCode === HttpCode.SUCCESS && res[1]?.statusCode === HttpCode.SUCCESS) {
        if (current === 1) {
          const { _data, radio, currentYearData } = getNewTableData(res[0].data || {}, res[1].data);
          setRatioTableData(radio[0]);
          setYearTableData(_data);
          const dataArray = [{ name: _date + '年', data: currentYearData }];
          _data.forEach((t: any) => {
            dataArray.push({
              name: t.title.split('参')[0],
              data: [t.plan, t.operate, t.settlement, t.guoneng, t.huineng],
            });
          });
          let head = tableHead_4;
          if (marketId === 'PXBNX') {
            head = tableHead_4_PXBNX;
          }
          setEhartDealYearBarData({
            XAXIS: head.map((t: any) => t.name),
            dataArray,
          });
        } else {
          //处理表格数据
          if (!res[1].data?.length) {
            return;
          }
          const data = getNewTableData(res[0].data || {}, res[1].data);
          const { value }: any = data;
          setDetailTableData(value[0]);
          setEchartsPlanMonthLineData({
            XAXIS: [
              '1月',
              '2月',
              '3月',
              '4月',
              '5月',
              '6月',
              '7月',
              '8月',
              '9月',
              '10月',
              '11月',
              '12月',
            ],
            dataArray: value[0],
          });
        }
      }
      setLoading(false);
    } catch (error) {
      throw new Error('获取数据失败');
      // 处理错误，例如显示错误信息
    }
  };

  React.useEffect(() => {
    updateFetch();
  }, [refreshCount]);

  const handleSave = () => {
    const param: any = {
      monthEle: {},
      stationId: form.getFieldValue('unit'),
      valueType: 'numerical',
      year: moment(formData.date).format('YYYY'),
      publish: false,
      yearEle: detailTableData[0].count,
    };
    Object.values(OPTION_KEY).map((_t: any, i: number) => {
      param.monthEle[i] = Number(detailTableData[0][OPTION_KEY[i + 1]]);
    });
    setDataCount(param.monthEle);
    setIsTimeShow(true);
  };

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <div className={styles.flex}>
          <Steps
            type="navigation"
            current={current}
            onChange={onTagChange}
            className={styles.stepBox}
          >
            <Step
              status="wait"
              icon={
                <span
                  className={styles.icon}
                  style={
                    current === 0
                      ? { border: '1px solid var(--bd-primary)', color: 'var(--bd-primary)' }
                      : {}
                  }
                >
                  1
                </span>
              }
              title={
                <span style={{ color: current === 0 ? 'var(--bd-primary)' : 'var(--font-a60)' }}>
                  月计划
                </span>
              }
            />
            <Step
              status="wait"
              icon={
                <span
                  className={styles.icon}
                  style={
                    current === 1
                      ? { border: '1px solid var(--bd-primary)', color: 'var(--font-primary)' }
                      : {}
                  }
                >
                  2
                </span>
              }
              title={
                <span style={{ color: current === 1 ? 'var(--bd-primary)' : 'var(--font-a60)' }}>
                  年计划
                </span>
              }
            />
          </Steps>
        </div>
        <div className={styles.header}>
          <Form
            form={form}
            initialValues={initialValues()}
            className={styles.formStyles}
            onFinish={_onFinish.run}
          >
            <Form.Item
              name="unit"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择交易单元' }]}
            >
              <Select
                style={{ width: 240 }}
                placeholder="选择交易单元"
                showSearch
                options={stations.map((t: any) => ({ label: t.label, value: t.value }))}
                onChange={() => {
                  onUnitChange();
                }}
                filterOption={(input, option) => {
                  return (option?.label as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }}
              />
            </Form.Item>
            <Form.Item
              name="date"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择年份234' }]}
            >
              <DatePicker
                className={styles.select_date}
                allowClear={false}
                picker="year"
                onChange={onDateChange}
              />
            </Form.Item>
            <Form.Item name="referenceYear" className={styles.cell_item}>
              <MySelect options={referenceYearOptions} />
            </Form.Item>
            {/* <Popconfirm
                                title="您选择的数据量较大，可能延长加载时间或引起页面崩溃，是否确认查询？"
                                visible={visible}
                                onVisibleChange={handleVisibleChange}
                                onConfirm={() => confirm.run()}
                                onCancel={() => setVisible(false)}
                                okText="确认"
                                cancelText="取消"
                            > */}
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
            {/* </Popconfirm> */}
          </Form>
        </div>
        {loading ? (
          <PageLoading />
        ) : (
          <>
            {current === 0 ? (
              detailTableData?.length ? (
                <>
                  <div style={{ flex: 1, height: 410 }}>
                    <ChartDealMonthLine data={echartsPlanMonthLineData} scale={reSize / 100} />
                  </div>
                  <div className={styles.driver} />
                  <div style={{ marginBottom: 24 }}>
                    <div className={styles.title}>
                      <span>月度计划发电明细</span>
                      {marketId === 'PXBNX' && (
                        <Button
                          type="link"
                          onClick={() => {
                            handleSave();
                            // setIsTimeShow(true);
                          }}
                        >
                          分时段录入
                        </Button>
                      )}
                    </div>
                    <MonthRatioTable
                      onValueChange={onValueChange}
                      setTableData={_setDetailData}
                      tableData={detailTableData}
                      tableHeader={tableHead_2}
                      isRatio={false}
                      onClick={_onAdjustValue}
                      editor={editable}
                    />
                  </div>
                </>
              ) : (
                <TRDefault type="emptysm" />
              )
            ) : (
              ''
            )}
            {current === 1 ? (
              ratioTableData?.length ? (
                <>
                  <div style={{ flex: 1, height: 410 }}>
                    <ChartDealAllPowerBar data={ehartDealYearBarData} scale={reSize / 100} />
                  </div>
                  <div className={styles.driver} />
                  <div style={{ marginBottom: 24 }}>
                    <div className={styles.title_2}>
                      <span style={{ paddingRight: 8 }}>
                        {form.getFieldValue('date').format('YYYY')}年计划电量
                      </span>
                      {editable ? (
                        <div onClick={_onMakePlan} className={styles.flex_1}>
                          {configureRadiusSvg()}
                        </div>
                      ) : (
                        ''
                      )}
                      <InputNumber
                        disabled={!editable}
                        defaultValue={inputValue}
                        size="small"
                        className={styles.my_input}
                        value={inputValue}
                        formatter={(value) => `${value}`}
                        parser={(value) => value!.replace('', '')}
                        min={0}
                        max={maxYearEle}
                        step={0.001}
                        onChange={onInputChange}
                      />
                    </div>
                    <YearRatioTable
                      tableData={yearTableData}
                      tableHeader={
                        yearTableData?.length
                          ? marketId === 'PXBNX'
                            ? tableHead_4_PXBNX
                            : tableHead_4
                          : []
                      }
                      setInputValue={setInputValue}
                      editor={editable}
                    />
                    <div className={styles.driver} />
                    <div className={styles.title}>月度分解比例</div>
                    <MonthRatioTable
                      onValueChange={onRatioChange}
                      tableData={ratioTableData}
                      tableHeader={tableHead_3}
                      onClick={_onSetScale}
                      editor={editable}
                    />
                  </div>
                </>
              ) : (
                <TRDefault type="emptysm" />
              )
            ) : (
              ''
            )}
            {ratioTableData?.length || detailTableData?.length ? (
              <div className={styles.flex_1} style={{ paddingBottom: 24 }}>
                <Button loading={btnLoading} className={styles.btn} onClick={onSetpHanlder}>
                  {current === 0 ? '下一步' : '上一步'}
                </Button>
                {editable ? (
                  <>
                    <Popconfirm
                      visible={showSavePop}
                      onCancel={(e) => {
                        e?.stopPropagation();
                        setShowSavePop(false);
                      }}
                      placement="top"
                      title={
                        isSave
                          ? '提示：确认保存？'
                          : '提示：长期电量计划选择的12个月电量未全部录入，确认保存？'
                      }
                      onConfirm={onSave}
                      okText="确认"
                      cancelText="取消"
                    >
                      <Button
                        className={styles.btn}
                        onClick={() => {
                          checked('save');
                        }}
                      >
                        保存
                      </Button>
                    </Popconfirm>
                    <Popconfirm
                      visible={showPublicPop}
                      onCancel={(e) => {
                        e?.stopPropagation();
                        setShowPublicPop(false);
                      }}
                      placement="top"
                      title={
                        isSave
                          ? '提示：确认发布？'
                          : '提示：长期电量计划选择的12个月电量未全部录入，确认发布？'
                      }
                      onConfirm={onPublic}
                      okText="确认"
                      cancelText="取消"
                    >
                      <Button
                        className={styles.submit}
                        type="primary"
                        htmlType="submit"
                        onClick={checked}
                      >
                        发布
                      </Button>
                    </Popconfirm>
                  </>
                ) : (
                  ''
                )}
              </div>
            ) : (
              ''
            )}
          </>
        )}
      </div>
    </ConfigProvider>
  );
};

export default PowerGenerationPlanSurvey;
